package com.doyens.gmall.order.controller;

import com.doyens.gmall.cart.client.CartFeignClient;
import com.doyens.gmall.common.constant.RedisConst;
import com.doyens.gmall.common.result.Result;
import com.doyens.gmall.common.util.AuthContextHolder;
import com.doyens.gmall.model.cart.CartInfo;
import com.doyens.gmall.model.order.OrderDetail;
import com.doyens.gmall.model.order.OrderInfo;
import com.doyens.gmall.model.user.UserAddress;
import com.doyens.gmall.order.service.OrderService;
import com.doyens.gmall.product.client.ProductFeignClient;
import com.doyens.gmall.user.client.UserFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("api/order")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(userId)) {
            //远程查询用户的地址列表
            List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
            map.put("userAddressList", userAddressList);

            //远程查询用户的选中的购物车数据
            List<CartInfo> cartInfoList = cartFeignClient.getCartCheckedList(userId);
            //CartInfo 转换成OrderDetail，在页面展示数据,页面的OrderDetail需要 skuId
            List<OrderDetail> orderDetailList = new ArrayList<>();
            cartInfoList.forEach(cartInfo -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setSkuNum(cartInfo.getSkuNum());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                //设置实时价格
                orderDetail.setOrderPrice(cartInfo.getSkuPrice());
                orderDetailList.add(orderDetail);
            });
            map.put("detailArrayList", orderDetailList);
            map.put("totalNum", orderDetailList.size());
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderDetailList(orderDetailList);
            orderInfo.sumTotalAmount();

            //生成流水号
            String tradeNo = orderService.getTradeNo(userId);
            map.put("tradeNo", tradeNo);

            map.put("totalAmount", orderInfo.getTotalAmount());
        }
        return Result.ok(map);
    }

    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        if (!orderService.checkTradeCode(tradeNo, userId)) {
            return Result.fail().message("不能重复提交订单！");
        }
        orderService.deleteTradeNo(userId);
        //验库存，需要对这个订单的所有商品都验库存
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //保存所有异步任务对象，监听所有异步任务的完成
        List<CompletableFuture> completableFutureList = new ArrayList<>();
        //保存异步任务中错误信息，校验不通过就保存。所有异步任务完成后，如果该list长度大于0，说明校验不通过
        List<String> errorList = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
            CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
                if (!orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum())) {
                    errorList.add(orderDetail.getSkuName() + "库存不够");
                }
            }, threadPoolExecutor);
            completableFutureList.add(completableFuture1);

            CompletableFuture<Void> completableFuture2 = CompletableFuture.runAsync(() -> {
                //远程查询最新的价格
                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                if (skuPrice.compareTo(orderDetail.getOrderPrice()) != 0) {
                    //目前redis中的数据跟数据库中不同步，远程调用cart项目的方法，重新从数据库加载到redis中
                    cartFeignClient.loadCartCache(userId);
                    errorList.add(orderDetail.getSkuName() + "价格有变动！");
                }
            }, threadPoolExecutor);
            completableFutureList.add(completableFuture2);

        }
        CompletableFuture[] completableFutures = completableFutureList.toArray(new CompletableFuture[completableFutureList.size()]);
        //等待所有异步任务的完成
        CompletableFuture.allOf(completableFutures).join();
        //如果校验不通过，返回错误信息
        if(errorList.size()>0){
            return Result.fail().message(StringUtils.join(errorList,","));
        }

        orderService.save(orderInfo);
        return Result.ok();
    }
}
